<?php
namespace app\index\controller;

use app\common\controller\IndexBase;
use app\common\helper\MingHelper;
use app\common\helper\SendSmsHelper;
use app\common\helper\WxHelper;
use app\common\logic\UserLogic;
use app\common\model\Archives;
use app\common\model\Category;
use app\common\model\lawyer\CategorySon;
use app\common\model\User;
use app\common\validate\UserValidate;
use app\index\validate\LoginValidate;
use app\index\validate\RegisterValidate;
use PhpOffice\PhpWord\Writer\PDF\TCPDF;
use think\exception\ValidateException;
use think\facade\View;
use think\helper\Str;

class Index extends IndexBase
{
    protected $user;
    protected $uid;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }
    
    public function index() {
        $this->redirect("/admin");
        return false;
        $code = input("code");
        if (empty($code)) {
            $this->redirect("/h5");
        }
        $openid = (new WxHelper())->codeToAccessToken($code)->getOpenid();
        if (empty($openid)) {
            $this->error('登录失败');
        }
        $user = UserLogic::findOrCreateUser($openid,[]);
        $this->success($user);
    }
    
    public function aboutus() {
        $view = [
            "hover" => "about"
        ];
        View::assign($view);
        return View::fetch();
    }
    
    public function service()
    {
        $where = [];
        $category_son_id = input('category','');
        if ($category_son_id) {
            $where[] = ['category_son_id','=',$category_son_id];
            $son = CategorySon::where("id",$category_son_id)->find();
        }
        $category = Category::with(['children'])->select();
        $goods = \app\common\model\Goods::order("category_son_id")
            ->where($where)
            ->paginate(['list_rows'=>10,"page"=>$this->page,"query"=>input()]);
        $view = [
            "hover" => "service",
            "goods" => $goods,
            "category" => $category,
            "category_son_id" => $category_son_id,
            "category_id" => !empty($son) ? $son->category_id : ''
        ];
        View::assign($view);
        return View::fetch();
    }
    
    public function case() {
        $view = [
            "hover" => "case"
        ];
        View::assign($view);
        return View::fetch();
    }
    
    public function contactus() {
        $view = [
            "hover" => "contact"
        ];
        View::assign($view);
        return View::fetch();
    }
    

    
    public function goods()
    {
        $id = input('id/d');
        if (empty($id)) $this->redirect("/");
        $goods = \app\common\model\Goods::find($id);
        if (!$goods) $this->redirect("/");
        $view = [
            "goods" => $goods,
            "hover" => "service"
        ];
        View::assign($view);
        return View::fetch();
    }
    

    public function search(){
        $key = input("param.key","","htmlspecialchars");
        $list = Archives::where("title","like","%{$key}%")
            ->paginate(["list_rows"=>10,"page"=>$this->page]);
        View::assign("arclist",$list);
        $fileName = $this->view_path . 'list_article_search.html'; // 模板文件
        return View::fetch($fileName);
    }

    public function login()
    {
        if ($this->request->isPost()) {
            $data = (new LoginValidate())->doCheck('login');
            UserLogic::login($data);
            $this->success();
        }
        return View::fetch();
    }

    public function password()
    {
        return View::fetch();
    }
    
    
    public function logout()
    {
        session("user",null);
        return $this->success();
    }

    public function register()
    {
        if ($this->request->isPost()) {
            $data = (new RegisterValidate())->doCheck('register');
            UserLogic::register($data);
            return $this->success();
        }
        $flag = md5(time() . 'htttttc');
        session('regflag',$flag);
        return View::fetch();
    }

    public function sendForgetSms()
    {
        $data = safeInput();
        $rule = [
            "tel|手机号" => "require|mobile",
            "flag|令牌" => "require",
            "username|用户名" => "require"
        ];
        try {
            $this->validate($data,$rule);
        } catch (ValidateException $exception) {
            return  $this->error($exception->getMessage());
        }
        if ($data['flag'] !== session("smsflag")) {
            return $this->error("发送失败，请刷新重试");
        }
        $user = User::where("username",$data['username'])
            ->where("tel",$data['tel'])->find();
        if (!$user) {
            return $this->error("用户不存在");
        }

        $code = Str::random(4,1);
        session("forget_" . $data["tel"],$code);
        $ming = new MingHelper();
        $tel = "+86" . $data['tel'];
        $result = json_decode($ming->sendSms($tel,$code),true);
        if (isset($result['SendStatusSet']) && $result['SendStatusSet'][0]['Code'] == "Ok") {
            session('smsflag',null);
            return $this->success();
        }
        return $this->error("发送失败，请刷新重试");
    }
    public function sendSms()
    {
        $data = safeInput();

        if ($data['flag'] !== session("regflag")) {
            return $this->error("发送失败，请刷新重试");
        }

        $rule = [
            "tel|手机号" => "require|mobile",
            "flag|令牌" => "require"
        ];
        try {
            $this->validate($data,$rule);
        } catch (ValidateException $exception) {
            return  $this->error($exception->getMessage());
        }
        $ming = new SendSmsHelper();
        $tel = $data['tel'];
        $result = $ming->sendSms($tel,'register');
        if ($result['code'] == 1) $this->success();
        return $this->error($result['msg']);
    }

}
